import {MotionType} from "./../consts/Def";

export default class EntityAnimCtl extends Laya.Script3D {
    constructor() { super(); }

    protected _animator:Laya.Animator;

    protected _book = {};

    protected _currentDefaultMotion:MotionType;


    /**
     * @inheritDoc
     */
    public onAwake():void{
        this._currentDefaultMotion = MotionType.idle;
        this._animator = this.owner.getChildAt(0).getComponent(Laya.Animator);
    }

    /**
     * @inheritDoc
     */
    public onUpdate():void{

    }

    /**
     * @inheritDoc
     */
    public onDestroy():void{

    }

    public registerMotion(type:MotionType, name:string):void{
        this._book[type] = name;

        if(type != MotionType.idle){
            let layer = this._animator.getControllerLayer(0);

            let state = layer.getAnimatorState(name);

            if(state){
                let sp = state.addScript(NoIdleAnimScript) as NoIdleAnimScript;

                sp.ctl = this;
            }
        }
    }

    protected _currentMotion:MotionType = MotionType.idle;

    public doMotion(type:MotionType):void{
        this._currentMotion = type;

        var name = this._book[type];

        if(type == MotionType.attacka){
            this._animator.play(name, 0, 0);
        }
        else{
            this._animator.crossFade(name, 0.3, 0, 0);
        }

        if(type == MotionType.idle || type == MotionType.run){
            this._currentDefaultMotion = type;
        }
    }

    public getMotion():MotionType{
        return this._currentMotion;
    }

    public doDefaultMotion():void{
        if(this._currentDefaultMotion != MotionType.none){
            this.doMotion(this._currentDefaultMotion);
        }
    }
    
}

class NoIdleAnimScript extends Laya.AnimatorStateScript{
    constructor(){
        super();
    }
    
    public ctl:EntityAnimCtl;

    /**
     * 动画状态开始时执行。
     */
    public onStateEnter():void {
        // console.log("动画开始播放了");
        // this._text.text = "动画状态：动画开始播放";
    }
        
    /**
     * 动画状态更新时执行。
     */
    public onStateUpdate():void {
        // console.log("动画状态更新了");
        // this._text.text = "动画状态：动画更新中";
    }
        
    /**
     * 动画状态退出时执行。
     */
    public onStateExit():void {
        // console.log("动画退出了");
        // this._text.text = "动画状态：动画开始退出";
        this.ctl.doDefaultMotion();
    }
}
